package com.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import com.constants.Constants;
import com.interceptor.OssQiNiuHelper;
import com.qiniu.storage.model.DefaultPutRet;
import com.utils.CommonUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.annotation.IgnoreAuth;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.entity.ConfigEntity;
import com.entity.EIException;
import com.service.ConfigService;
import com.utils.R;
import javax.servlet.http.HttpServletResponse;
/**
 * 上传文件映射表
 */
@RestController
@RequestMapping("file")
@SuppressWarnings({"unchecked","rawtypes"})
public class FileController{
	@Autowired
    private ConfigService configService;


	@Autowired
	private OssQiNiuHelper ossQiNiuHelper;

	@Value("${qiniu.domain}")
	private String fileDomain;

	/**
	 * 七牛云文件上传
	 *
	 * @param file 文件
	 * @return
	 */
	@RequestMapping("/upload")
	public  R upload(@RequestParam("file") MultipartFile file,String type) {
		if (file == null) {
			throw new EIException("上传文件不能为空");
		}
		try {
			FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
			String originalFilename = file.getOriginalFilename();
			String fileExtend = originalFilename.substring(originalFilename.lastIndexOf("."));
			String yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			//默认不指定key的情况下，以文件内容的hash值作为文件名
			String fileKey = UUID.randomUUID().toString().substring(0,16).replace("-", "") + "-" + yyyyMMddHHmmss + fileExtend;
			Map<String, Object> map = new HashMap<>();
			DefaultPutRet uploadInfo = ossQiNiuHelper.upload(fileInputStream, fileKey);
			map.put("fileName", uploadInfo.key);
			map.put("name", originalFilename);
			map.put("size", file.getSize());
			//七牛云文件私有下载地址（看自己七牛云公开还是私有配置）
//			map.put("url", "http://" + fileDomain + "/" + uploadInfo.key);
			map.put("url", fileDomain + "/" + uploadInfo.key);

//			return R.ok().put("file",fileDomain + "/" + uploadInfo.key);
			return R.ok().put("data",map);
		} catch (Exception e) {
			e.printStackTrace();
			throw new EIException("上传文件失败");
		}
	}

	/**
	 * 七牛云私有文件下载
	 *
	 * @param filename 文件名
	 * @return
	 */
	@GetMapping(value = "/private/file/{filename}")
	public void privateDownload(@PathVariable("filename") String filename, HttpServletResponse response) {
		if (filename.isEmpty()) {
			return;
		}
		try {
			String privateFile = ossQiNiuHelper.getPrivateFile(filename);
			response.sendRedirect(privateFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 七牛云文件下载
	 *
	 * @param filename 文件名
	 * @return
	 */
	@RequestMapping(value = "/file/{filename}", method = {RequestMethod.GET})
	public void download(@PathVariable("filename") String filename, HttpServletResponse response) {
		if (filename.isEmpty()) {
			return;
		}
		try {
			String privateFile = ossQiNiuHelper.getFile(filename);
			response.sendRedirect("http://" + privateFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 七牛云文件下载
	 *
	 * @param filename 文件名
	 * @return
	 */
	@RequestMapping(value = "/file/delete/{filename}", method = {RequestMethod.GET})
	public R delete(@PathVariable("filename") String filename, HttpServletResponse response) {
		if (filename.isEmpty()) {
			return R.error("文件不能为空");
		}
		try {
			boolean delete = ossQiNiuHelper.delete(filename);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.ok("文件删除成功");
	}

	/**
	 * 上传文件
	 */
//	@RequestMapping("/upload")
//	public R upload(@RequestParam("file") MultipartFile file,String type) throws Exception {
//		System.out.println(file.getOriginalFilename());
//		if (file.isEmpty()) {
//			throw new EIException("上传文件不能为空");
//		}
//		String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
//		File path = new File(ResourceUtils.getURL("classpath:static").getPath());
//		if(!path.exists()) {
//		    path = new File("");
//		}
//		System.out.println("path.getAbsolutePath()=="+path.getAbsolutePath());
//		String up ="upload/"+ CommonUtil.nowDate(Constants.DATE_FORMAT_DATE).replace("-", "/")+"/";
//
//		File upload = new File(path.getAbsolutePath(),up);
//		if(!upload.exists()) {
//		    upload.mkdirs();
//		}
//		String fileName = new Date().getTime()+"."+fileExt;
//		File dest = new File(upload.getAbsolutePath()+"/"+fileName);
//		file.transferTo(dest);
//		/**
//  		 * 如果使用idea或者eclipse重启项目，发现之前上传的图片或者文件丢失，将下面一行代码注释打开
//   		 * 请将以下的"D:\\springbootq33sd\\src\\main\\resources\\static\\upload"替换成你本地项目的upload路径，
// 		 * 并且项目路径不能存在中文、空格等特殊字符
// 		 */
////		FileUtils.copyFile(dest, new File("D:\\springbootq33sd\\src\\main\\resources\\static\\upload"+"/"+fileName)); /**修改了路径以后请将该行最前面的//注释去掉**/
//		if(StringUtils.isNotBlank(type) && type.equals("1")) {
//			ConfigEntity configEntity = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "faceFile"));
//			if(configEntity==null) {
//				configEntity = new ConfigEntity();
//				configEntity.setName("faceFile");
//				configEntity.setValue(fileName);
//			} else {
//				configEntity.setValue(fileName);
//			}
//			configService.insertOrUpdate(configEntity);
//		}
//		return R.ok().put("file",up+fileName);
//	}
//
//	/**
//	 * 下载文件
//	 */
//	@IgnoreAuth
//	@RequestMapping("/download")
//	public ResponseEntity<byte[]> download(@RequestParam String fileName) {
//		try {
//			File path = new File(ResourceUtils.getURL("classpath:static").getPath());
//			if(!path.exists()) {
//			    path = new File("");
//			}
//			File upload = new File(path.getAbsolutePath(),"/upload/");
//			if(!upload.exists()) {
//			    upload.mkdirs();
//			}
//			File file = new File(upload.getAbsolutePath()+"/"+fileName);
//			if(file.exists()){
//				/*if(!fileService.canRead(file, SessionManager.getSessionUser())){
//					getResponse().sendError(403);
//				}*/
//				HttpHeaders headers = new HttpHeaders();
//			    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//			    headers.setContentDispositionFormData("attachment", fileName);
//			    return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		return new ResponseEntity<byte[]>(HttpStatus.INTERNAL_SERVER_ERROR);
//	}
	
}
